package org.jeecg.modules.demo.util;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jeecg.modules.demo.Kingdee.Entity.ReceiptInfo;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 签名工具类
 */
@Component
@Slf4j
public class SignUtil {
    
    private static final String API_KEY = "fW77LfgwZPKi3FkyTnuv87BdI55ojbtZ";

    /**
     * 生成签名（保留原来的实现）
     */
    public String generateSign(Map<String, Object> params) {
        // 创建参数列表并排序
        List<NameValuePair> sortedParams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (!"sign".equals(entry.getKey())) {
                String valueStr;
                // 对于List类型的值，转换为JSON数组格式的字符串
                if (entry.getValue() instanceof List) {
                    valueStr = JSON.toJSONString(entry.getValue());
                } else {
                    valueStr = entry.getValue().toString();
                }
                sortedParams.add(new BasicNameValuePair(entry.getKey(), valueStr));
            }
        }
        sortedParams.sort(Comparator.comparing(NameValuePair::getName));

        // 拼接参数名和参数值
//        log.info("排序后的参数:");
        StringBuilder sb = new StringBuilder();
        for (NameValuePair param : sortedParams) {
            sb.append(param.getName()).append(param.getValue());
        }
//        log.info("拼接后的字符串: {}", sb.toString());
        // 拼接 appsecret
        sb.append(API_KEY);
//        log.info("拼接secret后的字符串: {}", sb.toString());
        // MD5 加密
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(sb.toString().getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            String result = hexString.toString();
            log.info("生成的签名: {}", result);
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }
    
    /**
     * 生成下载请求的签名（新的实现）
     *
     * @param timestamp 时间戳
     * @param userDataList 用户数据列表
     * @return 签名字符串
     */
    public static String generateDownloadSign(String timestamp, List<ReceiptInfo> userDataList) {
        // 按照对方系统的拼接顺序
        StringBuilder stringBuilder = new StringBuilder();
        
        // 先拼接timestamp参数
        stringBuilder.append("timestamp").append(timestamp);
        
        // 再拼接userDataList参数，使用=号格式而不是JSON格式
        if (userDataList != null && !userDataList.isEmpty()) {
            stringBuilder.append("userDataList").append("[");
            for (int i = 0; i < userDataList.size(); i++) {
                if (i > 0) {
                    stringBuilder.append(",");
                }
                ReceiptInfo info = userDataList.get(i);
                stringBuilder.append("{rcptNum=").append(info.getRcptNum()).append("}");
            }
            stringBuilder.append("]");
        }
        
        // 最后拼接appsecret
        stringBuilder.append(API_KEY);
        
//        log.info("下载请求拼接后的字符串: {}", stringBuilder.toString());
        
        // MD5加密
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] inputBytes = stringBuilder.toString().getBytes("UTF-8");
            byte[] hashBytes = md5.digest(inputBytes);

            // 将字节转换为十六进制字符串（确保每个字节都表示为两位十六进制数）
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0'); // 对于单位数的十六进制，在前面补0
                }
                hexString.append(hex);
            }

            String result = hexString.toString();
//            log.info("下载请求生成的签名: {}", result);
            return result; // 返回小写形式
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException("生成签名时发生错误", e);
        }
    }

    /**
     * 获取当前时间戳（毫秒）
     * @return 时间戳字符串
     */
    public static String getCurrentTimestamp() {
        return String.valueOf(System.currentTimeMillis());
    }
}